package com.nuaa.qianru.run;

import com.nuaa.qianru.dao.TpDao;
import com.nuaa.qianru.model.AlarmInfo;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class PushCallback19 implements MqttCallback,MqttCallbackExtended {

    @Autowired
    TpDao tpDao;

    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");

    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());

    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        String mess = new String(message.getPayload(),"UTF-8");//需要确定对应的编码格式

        if(!mess.equals("close")&&!mess.equals("")){
            //存储相关报警信息：时间、内容、编号
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");
            String time = format.format(date);

            AlarmInfo alarmInfo = new AlarmInfo();
            alarmInfo.setInfo(mess);
            alarmInfo.setLevel1("二级报警");//自己设置报警等级
            alarmInfo.setTime1(time);

//            try {
//                tpDao.insertAlarm3(alarmInfo);//存储到机床报警信息表中
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

        }
    }

    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        try {
            Client19.getClient().subscribe("AlarmInformation", 1);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}




